package jwtx

import (
	"context"
	// "encoding/json"
	"strconv"

	"github.com/golang-jwt/jwt"
)

const userIdKey = "jwtUserId"

func GetToken(secretKey string, iat int64, seconds int64, uid int64) (string, error) { // #24.04.27# 去除
	claims := make(jwt.MapClaims)
	claims["exp"] = iat + seconds
	claims["iat"] = iat
	claims[userIdKey] = uid
	token := jwt.New(jwt.SigningMethodHS256)
	token.Claims = claims
	return token.SignedString([]byte(secretKey))
}

func GetUserId(ctx context.Context) (int64, error) {
	// userId, err := ctx.Value(userIdKey).(json.Number).Int64()
	// return userId, err

	var userId int64
	if val := ctx.Value("userId"); val != nil {
		if id, err := strconv.ParseInt(val.(string), 10, 64); err == nil {
			userId = id
		}
	}

	return userId, nil
}
